#!/bin/bash

# ============================================
# Web3管理平台 - 智能更新脚本
# 支持热更新、回滚、A/B部署
# ============================================

set -e

readonly GREEN='\033[0;32m'
readonly BLUE='\033[0;34m'
readonly YELLOW='\033[1;33m'
readonly RED='\033[0;31m'
readonly NC='\033[0m'

# 获取当前版本
get_current_version() {
    if docker ps | grep -q web3-backend; then
        docker exec web3-backend curl -s http://localhost:8080/actuator/info 2>/dev/null | \
        grep -o '"version":"[^"]*"' | cut -d'"' -f4 || echo "unknown"
    else
        echo "offline"
    fi
}

# 检查更新
check_for_updates() {
    echo "🔍 检查更新..."

    if [[ -d ".git" ]]; then
        git fetch origin main
        LOCAL=$(git rev-parse HEAD)
        REMOTE=$(git rev-parse origin/main)

        if [[ "$LOCAL" != "$REMOTE" ]]; then
            COMMITS_BEHIND=$(git rev-list --count HEAD..origin/main)
            echo "✅ 发现更新: 落后 $COMMITS_BEHIND 个提交"
            git log --oneline HEAD..origin/main | head -5
            return 0
        else
            echo "✅ 已是最新版本"
            return 1
        fi
    else
        echo "⚠️  非Git仓库，无法自动检查更新"
        return 1
    fi
}

# 热更新 (零停机)
hot_update() {
    echo "🔥 执行热更新..."

    # 1. 创建备份
    create_backup

    # 2. 拉取最新代码
    git pull origin main

    # 3. 构建新镜像
    echo "📦 构建新镜像..."
    docker-compose build --quiet

    # 4. 滚动更新后端 (零停机)
    echo "🔄 滚动更新后端..."

    # 启动新的后端实例
    docker-compose up -d --scale backend=2 --no-recreate backend
    sleep 15

    # 检查新实例健康状态
    if curl -s http://localhost:8080/actuator/health >/dev/null; then
        echo "✅ 新实例健康检查通过"

        # 停止旧实例
        OLD_CONTAINER=$(docker ps --filter "name=web3-backend" --format "{{.Names}}" | head -1)
        docker stop $OLD_CONTAINER
        docker rm $OLD_CONTAINER

        # 重命名新实例
        docker-compose up -d --scale backend=1 backend
    else
        echo "❌ 新实例健康检查失败，回滚中..."
        rollback_update
        exit 1
    fi

    # 5. 更新前端 (快速切换)
    echo "🎨 更新前端..."
    docker-compose up -d --no-deps frontend

    echo "✅ 热更新完成"
}

# 创建备份
create_backup() {
    local backup_dir="backups/pre-update-$(date +%Y%m%d_%H%M%S)"
    mkdir -p $backup_dir

    echo "💾 创建备份: $backup_dir"

    # 备份数据库
    docker exec web3-mysql mysqldump -u root -p123456 web3_management > $backup_dir/database.sql

    # 备份配置
    cp .env $backup_dir/
    cp docker-compose.yml $backup_dir/

    # 记录当前版本
    echo "$(get_current_version)" > $backup_dir/version.txt
    git rev-parse HEAD > $backup_dir/commit.txt

    echo "✅ 备份完成"
}

# 回滚更新
rollback_update() {
    echo "🔄 执行回滚..."

    # 找到最新备份
    local latest_backup=$(ls -t backups/pre-update-* | head -1)
    if [[ -z "$latest_backup" ]]; then
        echo "❌ 找不到备份文件"
        exit 1
    fi

    echo "📂 使用备份: $latest_backup"

    # 回滚到备份的提交
    local backup_commit=$(cat $latest_backup/commit.txt)
    git reset --hard $backup_commit

    # 重新构建和启动
    docker-compose build --quiet
    docker-compose up -d

    echo "✅ 回滚完成"
}

# A/B部署 (蓝绿部署)
ab_deploy() {
    echo "🔵🟢 执行A/B部署..."

    # 检测当前是A还是B环境
    if docker ps --format "{{.Names}}" | grep -q "web3.*-a"; then
        CURRENT="a"
        TARGET="b"
    else
        CURRENT="b"
        TARGET="a"
    fi

    echo "当前环境: $CURRENT, 目标环境: $TARGET"

    # 创建目标环境
    echo "🚀 创建 $TARGET 环境..."
    COMPOSE_PROJECT_NAME="web3-$TARGET" docker-compose up -d

    # 等待目标环境就绪
    echo "⏳ 等待新环境就绪..."
    sleep 30

    # 健康检查
    if curl -s http://localhost:8080/actuator/health >/dev/null; then
        echo "✅ 新环境健康检查通过"

        # 切换流量 (更新Nginx配置)
        switch_traffic $TARGET

        # 等待一段时间确保稳定
        sleep 10

        # 销毁旧环境
        echo "🗑️  清理旧环境..."
        COMPOSE_PROJECT_NAME="web3-$CURRENT" docker-compose down

        echo "✅ A/B部署完成"
    else
        echo "❌ 新环境健康检查失败"
        COMPOSE_PROJECT_NAME="web3-$TARGET" docker-compose down
        exit 1
    fi
}

# 流量切换
switch_traffic() {
    local target_env=$1
    echo "🔄 切换流量到 $target_env 环境..."

    # 这里可以更新负载均衡器配置
    # 或者更新Nginx upstream配置

    echo "✅ 流量切换完成"
}

# 自动更新检查 (可用于cron)
auto_update_check() {
    if check_for_updates; then
        echo "📧 发现更新，发送通知..."

        # 可以集成通知服务
        # curl -X POST webhook_url -d "发现Web3管理平台更新"

        # 自动应用更新 (可选)
        if [[ "${AUTO_UPDATE:-false}" == "true" ]]; then
            echo "🤖 自动应用更新..."
            hot_update
        fi
    fi
}

# 性能监控
performance_monitor() {
    echo "📊 性能监控报告"
    echo "════════════════════════════════════════"

    # CPU和内存使用率
    docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}" $(docker ps --format "{{.Names}}" | grep web3-)

    echo ""
    echo "📈 应用指标:"

    # 后端健康指标
    backend_health=$(curl -s http://localhost:8080/actuator/health)
    echo "  后端状态: $(echo $backend_health | grep -o '"status":"[^"]*"' | cut -d'"' -f4)"

    # 数据库连接数
    db_connections=$(docker exec web3-mysql mysql -u root -p123456 -e "SHOW STATUS LIKE 'Threads_connected';" 2>/dev/null | tail -1 | awk '{print $2}')
    echo "  数据库连接: $db_connections"

    # 磁盘使用
    disk_usage=$(df -h . | tail -1 | awk '{print $5}')
    echo "  磁盘使用率: $disk_usage"
}

# 主菜单
show_menu() {
    clear
    echo -e "${BLUE}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║              Web3管理平台 - 智能部署中心                 ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"

    echo "当前版本: $(get_current_version)"
    echo ""
    echo "🚀 部署选项:"
    echo "  1) 热更新 (零停机)"
    echo "  2) A/B部署 (蓝绿)"
    echo "  3) 全量更新"
    echo "  4) 回滚上一版本"
    echo ""
    echo "📊 监控选项:"
    echo "  5) 性能监控"
    echo "  6) 实时状态"
    echo "  7) 查看日志"
    echo ""
    echo "🔧 维护选项:"
    echo "  8) 数据备份"
    echo "  9) 清理资源"
    echo "  10) 故障诊断"
    echo ""
    echo "  0) 退出"
    echo ""
}

# 主函数
main() {
    case ${1:-menu} in
        --hot-update)
            if check_for_updates; then
                hot_update
            else
                echo "✅ 已是最新版本"
            fi
            ;;
        --ab-deploy)
            ab_deploy
            ;;
        --rollback)
            rollback_update
            ;;
        --monitor)
            while true; do
                performance_monitor
                sleep 5
                clear
            done
            ;;
        --auto-check)
            auto_update_check
            ;;
        menu|*)
            while true; do
                show_menu
                read -p "请选择 (0-10): " choice
                case $choice in
                    1) check_for_updates && hot_update ;;
                    2) ab_deploy ;;
                    3) ./smart-deploy.sh --upgrade ;;
                    4) rollback_update ;;
                    5) performance_monitor; read -p "按Enter继续..." ;;
                    6) ./smart-deploy.sh --dashboard ;;
                    7) docker-compose logs -f ;;
                    8) create_backup ;;
                    9) docker system prune -f ;;
                    10) echo "🔧 运行: docker-compose ps && docker logs web3-backend --tail 50" ;;
                    0) exit 0 ;;
                    *) echo "❌ 无效选择" ;;
                esac
            done
            ;;
    esac
}

# 设置cron任务 (自动更新检查)
setup_auto_update() {
    echo "⏰ 设置自动更新检查..."

    # 添加cron任务，每小时检查一次更新
    (crontab -l 2>/dev/null; echo "0 * * * * cd $(pwd) && ./update.sh --auto-check") | crontab -

    echo "✅ 自动更新检查已设置 (每小时执行)"
}

# 执行主程序
main "$@"